const { Service } = require('egg');

const moment = require('moment');
const { v4: uuidV4 } = require('uuid');
const address_table = 'address';


class AddressService extends Service {
  // 地址列表
  async list(pageIndex = 1, pageSize = 10, order = 'create_time', method = 'desc') {
    try {
      const { id } = this.ctx.session;
      const list = await this.app.knex().select('address', 'user_name', 'user_phone', 'user_email', 'uuid')
        .from(address_table)
        .where({ create_by: id, is_delete: 0 })
        .orderBy(order, method)
        .limit(Number(pageSize))
        .offset((Number(pageIndex) - 1) * Number(pageSize));

      const count = await this.app.knex().count({ id: 'uuid' }).from(address_table)
        .where({ create_by: id, is_delete: 0 });

      return {
        count: count.id,
        list,
      };
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 新增地址
  async insert(address, user_email, user_phone, user_name) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      const instance = {
        uuid: uuidV4(),
        address, user_email, user_name, user_phone,
        create_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'),
        create_by: id,
        update_by: id,
        is_delete: 0,
      };

      const data = await this.app.knex().insert(instance).into(address_table)
        .returning('id');

      instance.id = data.id;

      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 更新地址
  async update(address, user_email, user_phone, user_name, uuid) {
    try {
      const instance = await this.app.knex().select('*').from(address_table)
        .where({ uuid });
      const time = moment();

      if (address) {
        instance.address = address;
      }

      if (user_email) {
        instance.user_email = user_email;
      }

      if (user_phone) {
        instance.user_phone = user_phone;
      }

      if (user_name) {
        instance.user_name = user_name;
      }

      instance.update_time = moment(time).format('YYYY-MM-DD HH:mm:ss');
      await this.app.knex(address_table).update(instance).where({ uuid });

      return instance;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

  // 删除地址
  async delete(ids) {
    try {
      const time = moment();
      const { id } = this.ctx.session;
      await this.app.knex(address_table)
        .update({ is_delete: 1, update_time: moment(time).format('YYYY-MM-DD HH:mm:ss'), update_by: id })
        .whereIn('uuid', ids);

      return;
    } catch (error) {
      console.log(error);
      throw 'service错误';
    }
  }

}

module.exports = AddressService;
